package com.auto.autoapp.ui.activity

import android.content.Intent
import android.graphics.Rect
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityUpVideoListenBinding
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.widgets.SimpleToolbar
import com.auto.autoapp.widgets.SettingItemView
import com.auto.autoapp.model.UpVideoListenSetting
import com.auto.autoapp.services.FloatingWindowService
import com.auto.autoapp.task.UpVideoListenTask
import com.ven.assists.stepper.StepManager

/**
 * 主播新视频监听并评论
 */
class UpVideoListenActivity : BaseActivity() {
    private lateinit var binding: ActivityUpVideoListenBinding
    override fun provideView(): View {
        binding = ActivityUpVideoListenBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle(intent.getStringExtra("title"))
    }

    override fun onInit() {
        // 填充已保存值（聚合对象）
        val up = SpUtil.getUpSettings()

//        binding.sivAnchorList.setValues(
//            mutableListOf(
//                "https://v.douyin.com/CX2pXvdBPcQ/ 8@9.com :2pm",
//                "https://v.douyin.com/eQ8i-WD1fNQ/ 3@8.com :5pm",
//                "https://v.douyin.com/31UlQkfZf0I/ 2@8.com :5pm"
//            )
//        )
        binding.sivAnchorList.setValues(up.anchorList)
        binding.sivIntervalSeconds.setValues(listOf(up.intervalDays.toString()))
        binding.sivCollectCount.setValues(listOf(up.retryCount.toString()))

        // 焦点滚动适配
        attachFocusScroll(binding.sivAnchorList)
        attachFocusScroll(binding.sivIntervalSeconds)
        attachFocusScroll(binding.sivCollectCount)

        binding.btnConfirm.setOnClickListener {
            val anchors =
                binding.sivAnchorList.getValues().map { it.trim() }.filter { it.isNotEmpty() }
            val intervalStr = binding.sivIntervalSeconds.getValues().firstOrNull()?.trim().orEmpty()
            val collectStr = binding.sivCollectCount.getValues().firstOrNull()?.trim().orEmpty()

            clearError(binding.sivAnchorList)
            clearError(binding.sivIntervalSeconds)
            clearError(binding.sivCollectCount)

            var hasError = false
            if (anchors.isEmpty()) {
                binding.sivAnchorList.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请至少填写一个主播地址"
                hasError = true
            }

            val intervalSeconds = intervalStr.toIntOrNull()
            if (intervalSeconds == null || intervalSeconds <= 0) {
                binding.sivIntervalSeconds.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入大于0的天数"
                hasError = true
            }

            val collectCount = collectStr.toIntOrNull()
            if (collectCount == null || collectCount <= 0) {
                binding.sivCollectCount.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入大于0的整数"
                hasError = true
            }

            if (hasError) {
                Toast.makeText(this, "请修正标红项后再确认", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            SpUtil.setUpSettings(
                UpVideoListenSetting(
                    anchorList = anchors,
                    intervalDays = intervalSeconds!!,
                    retryCount = collectCount!!
                )
            )

            if (FloatingWindowService.getInstance() == null) {
                val intent = Intent(this, FloatingWindowService::class.java)
                intent.action = "SHOW_FLOATING_WINDOW"
                startService(intent)
            }

            StepManager.isStop = true
            StepManager.execute(UpVideoListenTask::class.java, 1, begin = true)
        }
    }

    private fun clearError(item: SettingItemView) {
        item.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error = null
    }

    private fun attachFocusScroll(item: SettingItemView) {
        item.setOnChildFocusListener { target ->
            scrollToView(target)
        }
    }

    private fun scrollToView(target: View) {
        binding.scrollContent.post {
            val rect = Rect()
            target.getDrawingRect(rect)
            binding.scrollContent.offsetDescendantRectToMyCoords(target, rect)
            val y = (rect.top - dp(24)).coerceAtLeast(0)
            binding.scrollContent.smoothScrollTo(0, y)
        }
    }

    private fun dp(value: Int): Int {
        val d = resources.displayMetrics.density
        return (value * d).toInt()
    }
}